package com.qpf


import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.hssf.usermodel.HSSFSheet
import org.apache.poi.hssf.usermodel.HSSFRow
import org.apache.poi.hssf.usermodel.HSSFCell
import org.apache.poi.hssf.usermodel.HSSFCellStyle
import org.apache.poi.hssf.usermodel.HSSFFont
import org.apache.poi.ss.usermodel.FillPatternType
import org.apache.poi.ss.usermodel.HorizontalAlignment
import org.apache.poi.ss.usermodel.IndexedColors

class Xml2PoiExcel{
    public static final targetFolderPath = "E:/"
    private HSSFWorkbook hssfWorkbook
     
    public static void main(String[] args) {
        println('--------------------------------------------------')

        PoiExcelTools tools = new PoiExcelTools()
//        def list = tools.parse('D:/develop_kit/front_ws/FrontendFNB/WebContent/WEB-INF/config/tx_interface/block_data.xml')
//        println(list)
//        //准备测试数据
//        Map<String,String> excelContentMap = ["key1":"value1","key2":"value2"]
//        def header = ["应用模块", "原交易码", "原交易描述", "交易请求数据结构ID", "交易输出数据结构ID", "响应码描述", "备注"]
//
        //创建Excel表格
//        tools.createExcel("D:\\develop_kit\\front_ws\\FrontendFSF\\WebContent\\WEB-INF\\config\\tx_interface\\block_data_FG.xml",
//                "block_data_FG_前端")
        tools.createExcel("D:\\develop_kit\\front_ws\\com.drlsolution.core.fsf\\src\\main\\resources\\tx_interface\\block_data_SF.xml",
                "block_data_FG_后台")
    }
    
    /**
     * 创建Excel
     * @param excelContentMapList
     * @return
     */
    private void createExcel(String src, String dst){
 
        String excelFileName = targetFolderPath + dst + new Date().getTime() +".xls"
        String sheetName = "原交易列表"
        def header = ["应用模块", "原交易码", "原交易描述", "交易请求数据结构ID", "交易输出数据结构ID", "响应码描述", "备注"]

        //创建Excel工作簿
        this.hssfWorkbook = new HSSFWorkbook()

        HSSFSheet excelSheet = hssfWorkbook.createSheet(sheetName)
        //设置默认列宽
        excelSheet.setDefaultColumnWidth(22)
        //设置默认列宽
        excelSheet.setDefaultColumnWidth(22)
        //行
        HSSFRow hssfRow = null
        //列
        HSSFCell hssfCell = null
        hssfRow = excelSheet?.createRow(0)
        header?.eachWithIndex { String str, int index ->
            hssfCell = hssfRow?.createCell(index)
            if (hssfCell) {
                hssfCell.setCellValue(str)
                setHeaderCellStyle(hssfWorkbook,hssfCell)
            }
        }

        // createSheet(sheetName)
        def list = parse(src)
        list?.each() { Map info ->
            excelSheet = hssfWorkbook.createSheet(info['id'])
            //设置默认列宽
            excelSheet.setDefaultColumnWidth(22)
            //设置默认列宽
            excelSheet.setDefaultColumnWidth(22)
            createSheet(excelSheet, info)
        }


        FileOutputStream fileOutputStream = new FileOutputStream(excelFileName)
        hssfWorkbook.write(fileOutputStream)
    }

    private void createSheet(HSSFSheet excelSheet, Map<String, String> info) {
        //行
        HSSFRow hssfRow = null
        //列
        HSSFCell hssfCell = null
        hssfRow = excelSheet?.createRow(0)
        def desc = hssfRow?.createCell(1)
        desc.setCellValue("CopyBook描述")
        def desc_ = hssfRow?.createCell(2)
        desc_.setCellValue(info["text"])

        hssfRow = excelSheet?.createRow(2)
        desc = hssfRow?.createCell(1)
        desc.setCellValue("DS名")
        desc_ = hssfRow?.createCell(2)
        desc_.setCellValue(info['id'])

        hssfRow = excelSheet?.createRow(3)
        desc = hssfRow?.createCell(1)
        desc.setCellValue("名称")
        desc_ = hssfRow?.createCell(2)
        desc_.setCellValue(info['text'])

        hssfRow = excelSheet?.createRow(4)
        desc = hssfRow?.createCell(1)
        desc.setCellValue("类型")
        desc_ = hssfRow?.createCell(2)
        desc_.setCellValue('原交易请求')

        hssfRow = excelSheet?.createRow(5)
        desc = hssfRow?.createCell(1)
        desc.setCellValue("描述")

        hssfRow = excelSheet?.createRow(6)
        def headers = ["序号", "字段名", "字段描述", "长度", "类型", "类型含义", "备注"]
        headers?.eachWithIndex { String name, int index ->
            hssfCell = hssfRow?.createCell(index)
            hssfCell.setCellValue(name)
            setHeaderCellStyle(hssfWorkbook,hssfCell)
        }

        info.fields?.eachWithIndex { Map fields, int index ->
            hssfRow = excelSheet?.createRow(7 + index)
            hssfRow?.createCell(0).setCellValue(fields.seq)
            hssfRow?.createCell(1).setCellValue(fields.fld_name)
            hssfRow?.createCell(2).setCellValue(fields.note)
            hssfRow?.createCell(3).setCellValue(fields.spt_len)
            hssfRow?.createCell(4).setCellValue("A")
        }
    }
 
    /**
     * 设置表头单元格样式
     * @param hssfWorkbook
     * @param hssfCell
     */
    private void setHeaderCellStyle(HSSFWorkbook hssfWorkbook,HSSFCell hssfCell) {
        HSSFCellStyle hssfCellStyle = hssfWorkbook.createCellStyle()
 
        hssfCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND)
        hssfCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex())
        hssfCellStyle.setWrapText(true)
        hssfCellStyle.setAlignment(HorizontalAlignment.CENTER)
 
        HSSFFont hssfFont = hssfWorkbook.createFont()
        hssfFont.setBold(true)
        hssfCellStyle.setFont(hssfFont)
        hssfCell.setCellStyle(hssfCellStyle)

    }


    private List parse(file) {

        /**
        <?xml version="1.0" encoding="GB2312"?>
        <datablock:datablock xmlns:datablock="datablock.xsd">
        <item id="FGR00501" text="业务受理详细信息查询请求数据结构">
            <field>
            <seq>1</seq>
            <fld_name>GBH22JRN</fld_name>
            <use_dft>false</use_dft>
            <spt_fld_typ>String</spt_fld_typ>
            <spt_dec_pt>0</spt_dec_pt>
            <spt_len>22</spt_len>
            <ref_dbid></ref_dbid>
            <ref_db_many>false</ref_db_many>
            <note>业务受理登记流水号</note>
            </field>
        </item>
        </datablock>
        */
        def parser = new XmlParser()
        def doc = parser.parse(file)
        def list = []
        doc.item.each(){item ->
            def item_ = [id: item.attribute("id"), text: item.attribute("text")]
            def fields = []
            item.field.each(){ field ->
                fields.add([seq:field.seq[0]?.text(), fld_name:field.fld_name[0]?.text(), use_dft:field.use_dft[0]?.text(), dict_field_id:field.dict_field_id[0]?.text(), spt_fld_typ:field.spt_fld_typ[0]?.text(), spt_fmt_typ:field.spt_fmt_typ[0]?.text(), spt_dec_pt:field.spt_dec_pt[0]?.text(), spt_len:field.spt_len[0]?.text(), note:field.note[0]?.text(), ref_db_many:field.ref_db_many[0]?.text()])
            }
            item_['fields'] = fields
            list.add(item_)
        }
//        println("${list}")
        return list
    }
}